package org.dromara.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.lock.annotation.Lock4j;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ijpay.core.kit.WxPayKit;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.BusinessException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.MemberRecords;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.SysUserCommonConfig;
import org.dromara.system.domain.SysUserMemberConfig;
import org.dromara.system.domain.bo.*;
import org.dromara.system.domain.vo.AlipayNotifyParamVo;
import org.dromara.system.domain.vo.MemberRecordsVo;
import org.dromara.system.enums.MachineConstant;
import org.dromara.system.enums.PayTypeEnum;
import org.dromara.system.enums.SysUserFreezePointsRecordsEnum;
import org.dromara.system.mapper.MemberRecordsMapper;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.system.service.IMemberRecordsService;
import org.dromara.system.service.ISysUserCommonConfigService;
import org.dromara.system.service.ISysUserFreezePointsRecordsService;
import org.dromara.system.service.ISysUserMemberConfigService;
import org.dromara.system.service.impl.pay.AbstractPayService;
import org.dromara.system.service.impl.permission.PermissionBaseService;
import org.dromara.system.util.JsonUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 会员开通记录Service业务层处理
 *
 * @author Lion Li
 * @date 2025-07-18
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class MemberRecordsServiceImpl
    extends ServiceImpl<MemberRecordsMapper, MemberRecords> implements IMemberRecordsService {
    public static final String PREFIX = "TDM";
    private final SysUserMapper sysUserMapper;
    private final ISysUserCommonConfigService commonConfigService;
    private final PermissionBaseService permissionBaseService;
    private final ISysUserMemberConfigService sysUserMemberConfigService;
    private final ISysUserFreezePointsRecordsService sysUserFreezePointsRecordsService;
    @Resource
    private Map<String, AbstractPayService> abstractPayServiceMap;

    public static synchronized String getOrderNo(int digit) {
        StringBuilder resultBuffer = new StringBuilder();
        resultBuffer.append(PREFIX)
            .append(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
        Random random = new Random();
        for (int i = 0; i < digit; i++) {
            resultBuffer.append(random.nextInt(10));
        }
        return resultBuffer.toString();
    }

    /**
     * 查询会员开通记录
     *
     * @param id 主键
     * @return 会员开通记录
     */
    @Override
    public MemberRecordsVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询会员开通记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 会员开通记录分页列表
     */
    @Override
    public TableDataInfo<MemberRecordsVo> queryPageList(MemberRecordsBo bo, PageQuery pageQuery) {
        permissionBaseService.assignPermission(bo);
        IPage<MemberRecordsVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        IPage<MemberRecordsVo> list = baseMapper.findAll(page, bo);
        return TableDataInfo.build(list);
    }

    @Override
    public TableDataInfo<MemberRecordsVo> listReception(MemberRecordsBo bo, PageQuery pageQuery) {
        permissionBaseService.aloneAssignPermission(bo);
        IPage<MemberRecordsVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        IPage<MemberRecordsVo> list = baseMapper.findAll(page, bo);
        return TableDataInfo.build(list);
    }

    @Override
    public BigDecimal queryMemberPrice() {
        SysUser sysUser = sysUserMapper.selectById(LoginHelper.getUserId());
        Long oneId = sysUser.getOneId();
        SysUserCommonConfig sysUserCommonConfig = commonConfigService.lambdaQuery().eq(SysUserCommonConfig::getUserId, oneId).one();
        return Convert.toBigDecimal(sysUserCommonConfig.getMemberPrice(), BigDecimal.ZERO);
    }

    /**
     * 查询符合条件的会员开通记录列表
     *
     * @param bo 查询条件
     * @return 会员开通记录列表
     */
    @Override
    public List<MemberRecordsVo> queryList(MemberRecordsBo bo) {
        LambdaQueryWrapper<MemberRecords> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<MemberRecords> buildQueryWrapper(MemberRecordsBo bo) {
        LambdaQueryWrapper<MemberRecords> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(MemberRecords::getId);
        lqw.eq(bo.getUserId() != null, MemberRecords::getUserId, bo.getUserId());
        lqw.eq(bo.getPrice() != null, MemberRecords::getPrice, bo.getPrice());
        lqw.eq(bo.getStatus() != null, MemberRecords::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增会员开通记录
     *
     * @param bo 会员开通记录
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(MemberRecordsBo bo) {
        MemberRecords add = MapstructUtils.convert(bo, MemberRecords.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改会员开通记录
     *
     * @param bo 会员开通记录
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(MemberRecordsBo bo) {
        MemberRecords update = MapstructUtils.convert(bo, MemberRecords.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MemberRecords entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除会员开通记录信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public String openMemberShip(OpenMemberShipBo openMemberShipBo) {
        log.info("开通会员入参openMemberShip={}", JSONUtil.toJsonStr(openMemberShipBo));
        SysUser sysUser = sysUserMapper.selectById(LoginHelper.getUserId());
        SysUserMemberConfig sysUserMemberConfig = sysUserMemberConfigService.lambdaQuery()
            .eq(SysUserMemberConfig::getId, openMemberShipBo.getMemberConfigId()).one();
        AbstractPayService abstractCashBack = abstractPayServiceMap.get(
            PayTypeEnum.findOne(openMemberShipBo.getPayType()).getServiceName());
        MemberRecordsBo memberRecordsBo = MemberRecordsBo.builder()
            .no(getOrderNo(10))
            .memberConfigId(openMemberShipBo.getMemberConfigId())
            .userId(LoginHelper.getUserId())
            .status(MachineConstant.NUMBER.ZERO)
            .price(sysUserMemberConfig.getMemberPrice())
            .build();
        InitPayMemberBo initPayMemberBo = InitPayMemberBo.builder()
            .memberRecordsBo(memberRecordsBo)
            .sysUser(sysUser)
            .wechatCode(openMemberShipBo.getWechatCode())
            .openId(openMemberShipBo.getOpenId())
            .sysUserMemberConfig(sysUserMemberConfig)
            .build();
        String payMemberResult = abstractCashBack.initPayMember(initPayMemberBo);
        if (ObjectUtil.notEqual(PayTypeEnum.findOne(openMemberShipBo.getPayType()), PayTypeEnum.WECHAT)) {
            insertByBo(memberRecordsBo);
        }
        return payMemberResult;
    }

    @Override
    public String aliPayCallback(HttpServletRequest request) {
        Map<String, String> params = convertRequestParamsToMap(request); // 将异步通知中收到的待验证所有参数都存放到map中
        AlipayNotifyParamVo param = buildAlipayNotifyParam(params);
        try {
            MemberRecords memberRecords = lambdaQuery().eq(MemberRecords::getNo, param.getOutTradeNo()).one();
            if (ObjectUtil.isNull(memberRecords) || ObjectUtil.equal(memberRecords.getStatus(), MachineConstant.NUMBER.ONE)) {
                return "success";
            }
            if (StrUtil.equals(param.getTradeStatus(), "TRADE_SUCCESS") || StrUtil.equals(param.getTradeStatus(), "TRADE_FINISHED")) {
                dealMemberWork(memberRecords);
                return "success";
            }
        } catch (Exception e) {
            log.info("支付宝回调发生异常{}", e.toString());
        }
        return "failure";
    }

    @Override
    public String wxPayCallback(HttpServletRequest request, HttpServletResponse response) {
        try {
            String xmlMsg = readData(request);
            log.info("开通会员回调返回{}", JsonUtil.toJSONString(xmlMsg));
            Map<String, String> params = WxPayKit.xmlToMap(xmlMsg);
            log.info("开通会员回调返回转json{}", JsonUtil.toJSONString(params));
            String returnCode = params.get("return_code");
            if (WxPayKit.codeIsOk(returnCode) && WxPayKit.codeIsOk(returnCode)) {
                MemberRecordsBo attach = JSONUtil.toBean(params.get("attach"), MemberRecordsBo.class);
                attach.setStatus(MachineConstant.NUMBER.ONE);
                insertByBo(attach);
                MemberRecords memberRecords = lambdaQuery().eq(MemberRecords::getId, attach.getId()).one();
                dealMemberWork(memberRecords);
                Map<String, String> xml = new HashMap<String, String>(2);
                xml.put("return_code", "SUCCESS");
                xml.put("return_msg", "OK");
                return WxPayKit.toXml(xml);
            }
        } catch (Exception e) {
            log.info("微信支付回调失败：{}", e.toString());
        }
        return null;
    }


    public void dealMemberWork(MemberRecords memberRecords) {
        //将开通记录变为已支付状态  将用户会员标识加上
        lambdaUpdate().set(MemberRecords::getStatus, MachineConstant.NUMBER.ONE)
            .eq(MemberRecords::getId, memberRecords.getId())
            .update();
        LambdaUpdateWrapper<SysUser> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(SysUser::getMemberTag, memberRecords.getMemberConfigId());
        wrapper.eq(SysUser::getUserId, memberRecords.getUserId());
        sysUserMapper.update(wrapper);

        //给商户增加待返积分
        Long memberConfigId = memberRecords.getMemberConfigId();
        SysUserMemberConfig sysUserMemberConfig = sysUserMemberConfigService.lambdaQuery().eq(SysUserMemberConfig::getId, memberConfigId).one();
        BigDecimal memberPoints = sysUserMemberConfig.getMemberPoints();

        SysUserPurseBo sysUserPurseBoFrozen = SysUserPurseBo.builder()
            .userId(memberRecords.getUserId())
            .type(SysUserFreezePointsRecordsEnum.VIP_DECREASE_POINTS.getCode())
            .freezePoints(memberPoints)
            .build();
        sysUserFreezePointsRecordsService.updateUserFreezePoints(CollUtil.newArrayList(sysUserPurseBoFrozen));

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateUserMember(UpdateUserLevelBo bo) {
        SysUser sysUser = sysUserMapper.selectById(bo.getUserId());
        BusinessException.isTrue(ObjectUtil.notEqual(sysUser.getMemberTag(), MachineConstant.NUMBER.ZERO_L), "只能调整无会员等级的商户");
        BusinessException.isTrue(ObjectUtil.notEqual(sysUser.getOneId(), LoginHelper.getUserId()), "只能由所属一级代理调整等级");
        MemberRecordsBo memberRecordsBo = MemberRecordsBo.builder()
            .no(getOrderNo(10))
            .memberConfigId(bo.getMemberId())
            .userId(bo.getUserId())
            .status(MachineConstant.NUMBER.ZERO)
            .price(BigDecimal.ZERO)
            .remark("手动调整用户会员")
            .build();
        insertByBo(memberRecordsBo);
        MemberRecords memberRecords = lambdaQuery().eq(MemberRecords::getId, memberRecordsBo.getId()).one();
        dealMemberWork(memberRecords);
        return Boolean.TRUE;
    }

    // 将request中的参数转换成Map
    private Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<>();
        //1.从支付宝回调的request域中取值
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            retMap.put(name, valueStr);
        }
        return retMap;
    }

    private AlipayNotifyParamVo buildAlipayNotifyParam(Map<String, String> params) {
        String json = JSON.toJSONString(params);
        return JSON.parseObject(json, AlipayNotifyParamVo.class);
    }

    public String readData(HttpServletRequest request) {
        BufferedReader br = null;
        try {
            StringBuilder result = new StringBuilder();
            br = request.getReader();
            for (String line; (line = br.readLine()) != null; ) {
                if (result.length() > 0) {
                    result.append("\n");
                }
                result.append(line);
            }
            return result.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
